import { useState, useRef, useEffect, useMemo, useContext } from 'react';
import { useSearchParams } from 'next/navigation';
import MonacoEditor from './monaco-editor';
import ChatContent from './chat-content';
import ChatFeedback from './chat-feedback';
import { ChatContext } from '@/app/chat-context';
import { FeedBack, IChatDialogueMessageSchema } from '@/types/chat';
import classNames from 'classnames';
import { Empty, Modal, message, Tooltip } from 'antd';
import { renderModelIcon } from './header/model-selector';
import { cloneDeep } from 'lodash';
import copy from 'copy-to-clipboard';
import { useTranslation } from 'react-i18next';
import CompletionInput from '../common/completion-input';
import { useAsyncEffect } from 'ahooks';
import { STORAGE_INIT_MESSAGE_KET } from '@/utils';
import { Button, IconButton } from '@mui/joy';
import { CopyOutlined, RedoOutlined } from '@ant-design/icons';
import { getInitMessage } from '@/utils';
import { apiInterceptors, getChatFeedBackSelect } from '@/client/api';
import useSummary from '@/hooks/use-summary';

type Props = {
  messages: IChatDialogueMessageSchema[];
  onSubmit: (message: string, otherQueryBody?: Record<string, any>, text?: string) => Promise<void>;
  tempMsg: any;
  isLoading: boolean;
  setIsLoading: (val: boolean) => void;
  cancelRequest:()=> void;
};

const Completion = ({ messages, onSubmit, tempMsg, isLoading, setIsLoading, cancelRequest}: Props) => {
  const { dbParam, currentDialogue, scene, model, refreshDialogList, chatId, agentList, docId } = useContext(ChatContext);
  const { t } = useTranslation();
  const searchParams = useSearchParams();

  const spaceNameOriginal = (searchParams && searchParams.get('spaceNameOriginal')) ?? '';

  /* const [isLoading, setIsLoading] = useState(false); */
  const [jsonModalOpen, setJsonModalOpen] = useState(false);
  const [showMessages, setShowMessages] = useState(messages);
  console.log("showMessages",showMessages)
  const [jsonValue, setJsonValue] = useState<string>('');
  const [select_param, setSelectParam] = useState<FeedBack>();
  const scrollableRef = useRef<HTMLDivElement>(null);
  const isChartChat = useMemo(() => scene === 'chat_dashboard', [scene]);

  const summary = useSummary();
  const recorderTempMsg = useRef(null);
  const topSoundWave = useRef(null);
  const selectParam = useMemo(() => {
    switch (scene) {
      case 'chat_agent':
        return agentList.join(',');
      case 'chat_excel':
        return currentDialogue?.select_param;
      default:
        return spaceNameOriginal || dbParam;
    }
  }, [scene, agentList, currentDialogue, dbParam, spaceNameOriginal]);

  const handleChat = async (message: string) => {
    if (isLoading || !message.trim()) return;
    resetMessage();
    try {
      setIsLoading(true);
      const item = questions.find((question) => message.includes(question.desc));
      console.log(item);

      await onSubmit(
        message,
        {
          select_param: selectParam ?? '',
        },
        item?.text || '',
      ).then((res) => {
        console.log(1);
      });
    } finally {
      /* setIsLoading(false); */
    }
  };
  const handleIsRecorder = (value: boolean) => {
    /* setIsRecorder(value) */
    /*  scrollableRef.current?.scrollTo(0, scrollableRef.current?.scrollHeight - scrollableRef.current?.clientHeight); */
    setTimeout(() => {
      //console.log(scrollableRef.current?.scrollHeight);
      //console.log(scrollableRef.current?.clientHeight);
      scrollableRef.current?.scrollTo(0, scrollableRef.current?.scrollHeight - scrollableRef.current?.clientHeight);
    }, 400);
    topSoundWave.current.style.display = value ? 'flex' : 'none';
  };
  const updateTempMsg = (value: any) => {
    recorderTempMsg.current.innerText = value;
    handleIsRecorder(false);
  };
  const handleIsTempMsg = (value: boolean) => {
    recorderTempMsg.current.style.display = value ? 'flex' : 'none';
  };
  const handleJson2Obj = (jsonStr: string) => {
    try {
      return JSON.parse(jsonStr);
    } catch (e) {
      return jsonStr;
    }
  };

  const [messageApi, contextHolder] = message.useMessage();

  const onCopyContext = async (context: any) => {
    const pureStr = context?.replace(/\trelations:.*/g, '');
    const result = copy(pureStr);
    if (result) {
      if (pureStr) {
        messageApi.open({ type: 'success', content: t('Copy_success') });
      } else {
        messageApi.open({ type: 'warning', content: t('Copy_nothing') });
      }
    } else {
      messageApi.open({ type: 'error', content: t('Copry_error') });
    }
  };

  const handleRetry = async () => {
    if (isLoading || !docId) {
      return;
    }
    setIsLoading(true);
    await summary(docId);
    setIsLoading(false);
  };

  useAsyncEffect(async () => {
    const initMessage = getInitMessage();
    if (initMessage && initMessage.id === chatId) {
      await handleChat(initMessage.message);
      refreshDialogList();
      localStorage.removeItem(STORAGE_INIT_MESSAGE_KET);
    }
  }, [chatId]);

  const [lastChartIndex, setLastChartIndex] = useState(0);

  useEffect(() => {
    console.log('tempMsg',tempMsg);
    let tempMessage: IChatDialogueMessageSchema[] = messages;
    //console.log('tempMessage12',tempMessage)
    debugger
    //console.log("isChartChat",isChartChat)
    if (isChartChat) {
      
      tempMessage = cloneDeep(messages).map((item) => {
        if (item?.role === 'view' && typeof item?.context === 'string') {
          item.context = handleJson2Obj(item?.context);
        }
        return item;
      });
    }
    const temp = tempMessage.filter((item) => ['view', 'human'].includes(item.role));
    setShowMessages(temp);

    const _lastChartIndex = temp.findLastIndex((message) => {
      if (message.context) {
        return message.context.includes('chart-view');
      } else {
        return false;
      }
    });
    setLastChartIndex(_lastChartIndex);
  }, [isChartChat, messages, tempMsg]);

  useEffect(() => {
    apiInterceptors(getChatFeedBackSelect())
      .then((res) => {
        setSelectParam(res[1] ?? {});
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

  /*  useEffect(() => {
    setTimeout(() => {
      console.log(scrollableRef.current?.scrollHeight);
      console.log(scrollableRef.current?.clientHeight);
      scrollableRef.current?.scrollTo(0, scrollableRef.current?.scrollHeight - scrollableRef.current?.clientHeight);
    }, 400);
  }, [messages]); */
  // 监听消息变化有时候容易被高度变化给覆盖
  useEffect(() => {
    setTimeout(() => {
      // 假设messages是一个数组，存储着对话框中的每一条数据
      if (scrollableRef.current && messages.length > 1) {
        // 计算倒数第二条数据的DOM元素位置
        /* debugger; */
        /*  console.log(scrollableRef.current?.children[0]);
        console.log(scrollableRef.current?.children[0].children[scrollableRef.current?.children[0].children.length - 3].children[0].children[0]);
        console.log(scrollableRef.current?.children[0].children[0].children[0].children[0].innerText); */
        /* const secondToLastMessageElement = messages
          .slice(0, -1) // 获取除了最后一条之外的所有消息
          .map((item, index) => scrollableRef.current?.children[0].children[index].children[0].children[0].innerHTML) // 获取DOM元素
          .find(Boolean); // 找到最后一个存在的DOM元素
        console.log(secondToLastMessageElement); */
        const secondToLastMessageElement = isChildren(
          scrollableRef.current?.children[0].children[scrollableRef.current?.children[0].children.length - 3],
        );
        //console.log(secondToLastMessageElement);
        //debugger;
        // 让滚动区域滚动到该元素的位置
        if (secondToLastMessageElement) {
          secondToLastMessageElement.scrollIntoView({
            behavior: 'smooth',
            block: 'nearest',
            inline: 'end',
          });
        }
      }
      /* scrollableRef.current?.scrollTo(0, scrollableRef.current?.scrollHeight - scrollableRef.current?.clientHeight); */
    }, 400);
  }, [scrollableRef.current?.scrollHeight]);
  const isChildren = (dom: any) => {
    if (dom?.children.length > 0) {
      return isChildren(dom.children[0]);
    } else {
      //debugger;
      console.log(dom);
      return dom;
    }
  };
  const resetMessage = () => {
    const iframeDom = document.getElementById('numberPerson');
    iframeDom&&iframeDom?.contentWindow.postMessage({ text: "", eventType: 'reset' }, process.env.NEXT_PUBLIC_HUMAN_BASE_URL);
    breakTalk()
  };
  // 
  const breakTalk = () => {
    const iframeDom = document.getElementById('numberPerson');
    iframeDom&&iframeDom?.contentWindow.postMessage({ text: "", eventType: 'breakTalk' }, process.env.NEXT_PUBLIC_HUMAN_BASE_URL);
  };
  const questions = [
    {
      title: '我想要办理增值业务许可，我该怎么做？',
      desc: '我想要办理增值业务许可，我该怎么做？',
      text: '我想要办理增值业务许可，我该怎么做？',
    },
    {
      title: '我想要进行APP和网站备案，我该怎么办？',
      desc: '我想要进行APP和网站备案，我该怎么办？',
      text: '我想要进行APP和网站备案，我该怎么办？',
    },
    {
      title: '分析下广东省通信业主要指标完成情况',
      desc: '分析下广东省通信业主要指标完成情况',
      text: '分析下广东省通信业主要指标完成情况',
    },
    {
      title: '广州市电信业务总量和电信业务收入',
      desc: '广州市电信业务总量和电信业务收入',
      text: '广州市电信业务总量和电信业务收入',
    },
    {
      title: '帮我打开一下区域分析',
      desc: '帮我打开一下区域分析',
      text: '帮我打开一下区域分析',
    },
  ];
  // 用useState会导致录音失败改为直接操作dom
  /*  let [isRecorder,setIsRecorder] = useState(false) */
  /*  let isRecorder = false */
  /* useEffect(()=>{
    console.log(isRecorder)
  },[isRecorder]) */
  const messageRef = useRef(null);

  return (
    <>
      {contextHolder}
      <div
        ref={scrollableRef}
        className="flex px-4 flex-1 overflow-y-auto pb-4 w-full flex-col"
        style={{ height: 'calc(100% - 110vh * var(--h))', width: 'calc(100% - 0px)', display: 'inline-block' }}
      >
        <div className="flex items-center flex-1 flex-col text-sm leading-6 text-slate-900 dark:text-slate-300 sm:text-base sm:leading-7">
          {showMessages.length ? (
            showMessages.map((content, index) => {
              return (
                <ChatContent
                  key={index}
                  content={content}
                  isChartChat={isChartChat}
                  isLoading={isLoading}
                  setIsLoading={setIsLoading}
                  isLastChart={lastChartIndex === index}
                  handleIsRecorder={handleIsRecorder}
                  cancelRequest={cancelRequest}
                  isLast={showMessages.length-1 === index}
                  onLinkClick={() => {
                    setJsonModalOpen(true);
                    setJsonValue(JSON.stringify(content?.context, null, 2));
                  }}
                >
                  {/* {content.role === 'view' && (
                    <div className="flex w-full pt-2 md:pt-4 border-t border-gray-200 mt-2 md:mt-4 pl-2">
                      {scene === 'chat_knowledge' && content.retry ? (
                        <Button onClick={handleRetry} slots={{ root: IconButton }} slotProps={{ root: { variant: 'plain', color: 'primary' } }}>
                          <RedoOutlined />
                          &nbsp;<span className="text-sm">{t('Retry')}</span>
                        </Button>
                      ) : null}
                      <div className="flex w-full flex-row-reverse">
                        <ChatFeedback
                          select_param={select_param}
                          conv_index={Math.ceil((index + 1) / 2)}
                          question={showMessages?.filter((e) => e?.role === 'human' && e?.order === content.order)[0]?.context}
                          knowledge_space={spaceNameOriginal || dbParam || ''}
                        />
                        <Tooltip title={t('Copy')}>
                          <Button
                            onClick={() => onCopyContext(content?.context)}
                            slots={{ root: IconButton }}
                            slotProps={{ root: { variant: 'plain', color: 'primary' } }}
                            sx={{ borderRadius: 40 }}
                          >
                            <CopyOutlined />
                          </Button>
                        </Tooltip>
                      </div>
                    </div>
                  )} */}
                </ChatContent>
              );
            })
          ) : (
            // <Empty
            //   image="/empty.png"
            //   imageStyle={{ width: 320, height: 320, margin: '0 auto', maxWidth: '100%', maxHeight: '100%' }}
            //   className="flex items-center justify-center flex-col h-full w-full"
            //   description=""
            // />
            <div className="tipMessage">
              <img src="../head.png" onClick={resetMessage} alt="" className="robotSize" />
              <span className="tipTitle">请输入您的提问内容</span>
            </div>
          )}
          {
            <div className="topSoundWave">
              <div className="soundWave" ref={topSoundWave} style={{ display: 'none' }}>
                <div className="boxWave">
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 0.5s linear infinite alternate forwards' }}></span>
                  <span style={{ animation: 'stretch 1s 1s linear infinite alternate forwards' }}></span>
                </div>
              </div>
              <span className="custom-chat-bg recorderTempMsg" style={{ display: 'none' }} ref={recorderTempMsg}></span>
            </div>
          }
        </div>
      </div>
      <div className="boxMessage" style={{ boxShadow: '0px -4px 10px 0px rgba(114,148,199,0.25)' }}>
        <div className="guess-like">
          <div className="left">猜你想问</div>
          <div className="right">
            {questions.map((question: { title: string; desc: string }) => (
              <div
                key={question.title}
                className="question"
                onClick={() => {
                  console.log(messageRef);
                  messageRef.current?.insertUserInput(question.desc);
                }}
              >
                {question.title}
              </div>
            ))}
          </div>
        </div>
        <div
          className={classNames('dark:after:from-[#212121]', {
            'cursor-not-allowed': scene === 'chat_excel' && !currentDialogue?.select_param,
          })}
          style={{ height: 'calc(55vh * var(--h))', width: 'calc(100% - 0px)' /* borderTop: '1px solid #48A8FF' */ }}
        >
          <div className="flex flex-wrap w-full items-center" style={{ height: '100%' }}>
            {/* {model && <div className="mr-2 flex">{renderModelIcon(model)}</div>} */}
            <CompletionInput
              loading={isLoading}
              onSubmit={handleChat}
              handleIsRecorder={handleIsRecorder}
              handleFinish={setIsLoading}
              ref={messageRef}
              updateTempMsg={updateTempMsg}
              handleIsTempMsg={handleIsTempMsg}
            />
          </div>
        </div>
      </div>

      <Modal
        title="JSON Editor"
        open={jsonModalOpen}
        width="60%"
        cancelButtonProps={{
          hidden: true,
        }}
        onOk={() => {
          setJsonModalOpen(false);
        }}
        onCancel={() => {
          setJsonModalOpen(false);
        }}
      >
        <MonacoEditor className="w-full h-[500px]" language="json" value={jsonValue} />
      </Modal>
    </>
  );
};

export default Completion;
